from typing import List


class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        n = len(nums)
        nums.sort()
        sim = float('inf')
        result = 0
        for i in range(n):
            left = i + 1
            right = n - 1
            while left < right:
                if nums[left] + nums[right] + nums[i] < target:
                    left += 1
                    if abs(nums[left] + nums[right] + nums[i] - target) < sim:
                        sim = abs(nums[left] + nums[right] + nums[i] - target)
                        result = nums[left] + nums[right] + nums[i]
                elif nums[left] + nums[right] + nums[i] > target:

                    if abs(nums[left] + nums[right] + nums[i] - target) < sim:
                        sim = abs(nums[left] + nums[right] + nums[i] - target)
                        result = nums[left] + nums[right] + nums[i]
                else:
                    return target
        return result


if __name__ == '__main__':
    s = Solution()
    r = s.threeSumClosest(nums=[-1, 2, 1, -4], target=1)
    print(r)
